import Vue from "vue";
import store from "../store";
// import { Button } from "element-ui";
Vue.directive("drag", {
  bind(el, binding) {
    // 鼠标按下
    el.onmousedown = (e) => {
      let cyBtn = document.createElement("div"); //复制一份el主体
      let lefts = "";
      let mainList = {};
      console.log(cyBtn);
      cyBtn.setAttribute("id", "drag"); //给标签添加一个id
      cyBtn.style.position = "absolute"; //修改元素的熟悉感
      cyBtn.style.width = "300px";
      cyBtn.style.lineHeight = "28px";
      cyBtn.style.background = "#409EFF";
      cyBtn.style.textAlign = "center";
      cyBtn.style.color = "white";
       cyBtn.style.cursor = "pointer";
      cyBtn.innerHTML = JSON.parse(binding.value).tableName; //插入组件名
      let body = document.body; //获取body对象
      body.appendChild(cyBtn); //在body下面插入子节点的主题
      // 算出鼠标相对元素的位置
      let disX = e.clientX - el.offsetLeft; //x轴坐标
      let disY = e.clientY - el.offsetTop; //y轴坐标
      let top = "";
      let tops = "";
      let tableTop = null;
      tableTop = document.getElementById("boardTops").offsetHeight;
      document.onmousemove = (e) => {
        //鼠标按下并移动的事件
        //用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
        let left = e.clientX - disX; //  鼠标停留 计算出相对位置
        top = e.clientY - disY; //  鼠标停留 计算出相对位置
        lefts = left - document.querySelector("#boardTops").offsetLeft;
        tops = top - document.querySelector("#boardTops").offsetTop;
        document.querySelector("#drag").style.left = `${left + 200}px`;
        document.querySelector("#drag").style.top = `${top}px`;
      };
      // 鼠标松开
      document.onmouseup = () => {
        document.onmousemove = null; //清除移动事件
        document.onmouseup = null; //清除鼠标移开事件
        let isTableTop = tops - tableTop;
        console.log("距离", isTableTop, tops, tableTop);
        if (lefts > 0 && tops>0 && isTableTop < 0) { //判断可放置的区域是否在画布区域内
          mainList = {
            x: lefts,
            y: tops,
            ...JSON.parse(binding.value),
          };
          store.dispatch('app/mapListBtn', mainList)
        //   store.commit("mapListBtn", mainList); //存放带vuex中
        }
        document.getElementById("drag").remove(); //删除元素id
      };
    };
  },
});